package me.leiusual.sharing.ui.order

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_order_list.*
import me.leiusual.sharing.R
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.order.adapter.OrderListParentAdapter
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-31
 * description:
 */
class OrderListFragment : DaggerFragment() {

  companion object {
    private const val STORE_ID = "storeId"
    private const val STATUS = "status"

    /**
     * 订单列表
     * @param storeId 店铺id：0表示用户订单，>0表示店铺订单
     * @param status 订单状态：1待支付，2待发货，3待收货，0全部
     */
    fun newInstance(storeId: Long, status: Int): OrderListFragment {
      return OrderListFragment().apply {
        val args = Bundle()
        args.putLong(STORE_ID, storeId)
        args.putInt(STATUS, status)
        arguments = args
      }
    }
  }

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  private val viewModel: OrderListViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_order_list, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recycler_view.adapter = OrderListParentAdapter {
      Timber.v("点击：%s", it)

      val storeId = arguments?.getLong(STORE_ID) ?: 0
      val action = OrderHomeFragmentDirections.actionOrderHomeFragmentToOrderDetailFragment(storeId, it.code)
      findNavController().navigate(action)
    }

    observeData()
    viewModel.orderList(arguments?.getLong(STORE_ID) ?: 0, arguments?.getInt(STATUS) ?: 0)
  }

  private fun observeData() {
    viewModel.loadInitial.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("loadInitial = %s", it)
      when (it) {
        is Data.Loading -> {
          // ignore
        }
        is Data.Error -> {
          // ignore
        }
        is Data.Success -> {
          mainViewModel.orderCount(it.data.stateCountMap)
        }
      }
    })

    viewModel.orderList.observe(viewLifecycleOwner, Observer {
      Timber.v("orderList = %s", it)

      val adapter = recycler_view.adapter as OrderListParentAdapter
      adapter.submitList(it)
    })
  }
}